<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script>
  <link href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">



<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("http://xxxxxxx.xxx"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>





<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="zrNUWIf25v2J4dC1wliso_DUXEwYoECv4j3h9CE34xM">








  <meta name="baidu-site-verification" content="nuHze5uXZ7">







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">




<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.2',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="利用docker快速搭建LNMP环境">
<meta name="keywords" content="linux,docker,php,nginx,mysql">
<meta property="og:type" content="article">
<meta property="og:title" content="docker快速搭建php nginx mysql环境">
<meta property="og:url" content="https://blog.codenote.pro/docker-quickly-build-php-nginx-mysql-environment.html">
<meta property="og:site_name" content="九阳的笔记本">
<meta property="og:description" content="利用docker快速搭建LNMP环境">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://img.codenote.pro/3070617114.png">
<meta property="og:image" content="http://static.notemi.cn/notemi/2018/04/1903420531.png">
<meta property="og:image" content="http://static.notemi.cn/notemi/2018/04/4034020030.png">
<meta property="og:image" content="http://static.notemi.cn/notemi/2018/04/409938554.png">
<meta property="og:image" content="https://notemi.cn/usr/plugins/Smilies/hangout/icon_lol.png">
<meta property="og:updated_time" content="2018-11-02T15:43:49.618Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="docker快速搭建php nginx mysql环境">
<meta name="twitter:description" content="利用docker快速搭建LNMP环境">
<meta name="twitter:image" content="https://img.codenote.pro/3070617114.png">



  <link rel="alternate" href="/atom.xml" title="九阳的笔记本" type="application/atom+xml">




  <link rel="canonical" href="https://blog.codenote.pro/docker-quickly-build-php-nginx-mysql-environment.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>docker快速搭建php nginx mysql环境 | 九阳的笔记本</title>
  




<script async src="https://www.googletagmanager.com/gtag/js?id=UA-126970002-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-126970002-1');
</script>



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07b2f6778635ec267ee2b4753e118da9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
     
    
    
    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">九阳的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-hexo">
    <a href="/categories/Hexo" rel="section">
      <i class="menu-item-icon fa fa-fw fa-header"></i> <br>Hexo</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-linux">
    <a href="/categories/Linux" rel="section">
      <i class="menu-item-icon fa fa-fw fa-linux"></i> <br>Linux</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-docker">
    <a href="/categories/docker" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>docker</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-learn">
    <a href="/categories/learn" rel="section">
      <i class="menu-item-icon fa fa-fw fa-leanpub"></i> <br>学习</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br>阅读排行</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.codenote.pro/docker-quickly-build-php-nginx-mysql-environment.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yszar">
      <meta itemprop="description" content="学无止境！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="九阳的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">docker快速搭建php nginx mysql环境
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-07 15:14:04" itemprop="dateCreated datePublished" datetime="2018-10-07T15:14:04+08:00">2018-10-07</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-02 23:43:49" itemprop="dateModified" datetime="2018-11-02T23:43:49+08:00">2018-11-02</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Linux/" itemprop="url" rel="index"><span itemprop="name">Linux</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/docker-quickly-build-php-nginx-mysql-environment.html" class="leancloud_visitors" data-flag-title="docker快速搭建php nginx mysql环境">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p class="description">利用docker快速搭建LNMP环境</p>

<p><img src="https://img.codenote.pro/3070617114.png" alt="" style="width:100%"></p>
<a id="more"></a>
<h2 id="目标"><a href="#目标" class="headerlink" title="目标"></a>目标</h2><p>部署好mysql，php，nginx，运行一个php程序</p>
<h2 id="安装Docker"><a href="#安装Docker" class="headerlink" title="安装Docker"></a>安装Docker</h2><p>看这个：<a href="https://yeasy.gitbooks.io/docker_practice/" rel="external nofollow noopener noreferrer" target="_blank">https://yeasy.gitbooks.io/docker_practice/</a></p>
<h2 id="创建资源文件夹"><a href="#创建资源文件夹" class="headerlink" title="创建资源文件夹"></a>创建资源文件夹</h2><p>既然安装好了Docker，我们创建容器后，我们需要映射一些配置文件或网站程序文件到宿主机，所以我们创建一些文件夹来存放这些东西，我是创建了以下这些文件夹，你可以按照自己平时的习惯来创建。</p>
<figure class="highlight plain"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></div><div class="code"><pre><div class="line">/data</div><div class="line">/mysql  存放数据库备份</div><div class="line">/nginx  nginx配置文件</div><div class="line">/conf</div><div class="line">/wwwroot  网站文件</div><div class="line">/wwwlogs  日志</div><div class="line">/source  程序源代码</div><div class="line">/download 下载目录</div></pre></div></div></figure>
<h2 id="部署Mysql"><a href="#部署Mysql" class="headerlink" title="部署Mysql"></a>部署Mysql</h2><h3 id="1-拉取镜像"><a href="#1-拉取镜像" class="headerlink" title="1. 拉取镜像"></a>1. 拉取镜像</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># docker pull mysql:5.7</span></div></pre></div></div></figure>
<h3 id="2-运行容器"><a href="#2-运行容器" class="headerlink" title="2. 运行容器"></a>2. 运行容器</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># docker run \</span></div><div class="line">-d \</div><div class="line">-p 3306:3306 \</div><div class="line">-e MYSQL_ROOT_PASSWORD=12345678910 \</div><div class="line">--name m_mysql mysql:5.7</div></pre></div></div></figure>
<blockquote class="question">参数说明<br> -d 让容器在后台运行<br> -p 添加主机到容器的端口映射，前面是映射到本地的端口，后面是需要映射的端口<br> -e 设置环境变量，MYSQL_ROOT_PASSWORD这里是设置mysql的root用户的初始密码<br> –name 容器的名字，随便取，但是必须唯一<br></blockquote>

<div class="note info no-icon"><p>ps:其实我们可以仅仅使用docker run命令就行了。docker run会先去pull，然后再create。个人习惯先把镜像pull下来，在run的时候会很快。</p></div>

<h3 id="3-进入容器"><a href="#3-进入容器" class="headerlink" title="3. 进入容器"></a>3. 进入容器</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">docker <span class="built_in">exec</span> -it m_mysql /bin/bash</div></pre></div></div></figure>
<blockquote class="question">参数说明<br> -t 在容器里生产一个伪终端<br> -i 对容器内的标准输入 (STDIN) 进行交互</blockquote>

<p>容器中默认是没有vim的，所以我们首先要安装vim,需要注意的是安装前记得先执行<code>apt-get update</code>命令，不然安装会出现问题。</p>
<h3 id="4-开启Mysql远程连接"><a href="#4-开启Mysql远程连接" class="headerlink" title="4. 开启Mysql远程连接"></a>4. 开启Mysql远程连接</h3><p>这步你当然也可以不开启，可以使用ssh通道来连接，但是我这里记一笔。这里是5.7，注意了。</p>
<ol>
<li>进入mysql</li>
</ol>
<figure class="highlight sql"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">mysql -uroot -p12345678910</div></pre></div></div></figure>
<ol start="2">
<li>选择数据库</li>
</ol>
<figure class="highlight"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">&gt; use mysql</div></pre></div></div></figure>
<ol start="3">
<li>开启远程连接</li>
</ol>
<figure class="highlight sql"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></div><div class="code"><pre><div class="line"><span class="keyword">GRANT</span> ALL <span class="keyword">PRIVILEGES</span> <span class="keyword">ON</span> *.* <span class="keyword">TO</span> <span class="string">'root'</span>@<span class="string">'%'</span> <span class="keyword">IDENTIFIED</span> <span class="keyword">BY</span> <span class="string">'password'</span> <span class="keyword">WITH</span> <span class="keyword">GRANT</span> <span class="keyword">OPTION</span>;</div><div class="line"><span class="keyword">FLUSH</span> <span class="keyword">PRIVILEGES</span>;</div></pre></div></div></figure>
<p>4.重启</p>
<figure class="highlight sh"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">service mysqld restart</div></pre></div></div></figure>
<p>这样就可以通过公网IP连接了，如果还是不行，请看看防火墙(自身防火墙或者各大云服务商的安全组配置)。</p>
<h2 id="部署PHP"><a href="#部署PHP" class="headerlink" title="部署PHP"></a>部署PHP</h2><h3 id="1-拉取镜像-1"><a href="#1-拉取镜像-1" class="headerlink" title="1. 拉取镜像"></a>1. 拉取镜像</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">docker pull bitnami/php-fpm:7.0</div></pre></div></div></figure>
<h3 id="2-运行容器-1"><a href="#2-运行容器-1" class="headerlink" title="2. 运行容器"></a>2. 运行容器</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></div><div class="code"><pre><div class="line">docker run \</div><div class="line">-d \</div><div class="line">-p 9000:9000 \</div><div class="line">-v /data/wwwroot:/usr/share/nginx/html \</div><div class="line">--link m_mysql:mysql \</div><div class="line">--name m_phpfpm bitnami/php-fpm:7.0</div></pre></div></div></figure>
 <blockquote class="question">内容参数说明<br> -d 让容器在后台运行<br> -p 添加主机到容器的端口映射<br> -v 添加目录映射<br> –-name 容器的名字，随便取，但是必须唯一<br> –link link 是在两个contain之间建立一种父子关系，父container中的web，可以得到子container db上的信息。<br> 通过link的方式创建容器，我们可以使用被Link容器的别名进行访问，而不是通过IP，解除了对IP的依赖。</blockquote>

<h3 id="3-创建php文件"><a href="#3-创建php文件" class="headerlink" title="3. 创建php文件"></a>3. 创建php文件</h3><p>在<code>/data/wwwroot</code>文件夹中创建一个文件夹<code>default</code>，代表一个默认的工作目录，在<code>default</code>中创建一个文件</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">touch index.php</div></pre></div></div></figure>
<p>编辑index.php</p>
<figure class="highlight php"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></div><div class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">    <span class="keyword">echo</span> <span class="string">"hello!"</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></div></div></figure>
<p>这时候你进php容器，在<code>/usr/share/nginx/html</code>文件夹中也能看到我们创建的index.php文件，因为我们设置了目录映射。这样我们就可以直接在宿主机直接更改，而不用进容器修改。</p>
<h2 id="配置Nginx"><a href="#配置Nginx" class="headerlink" title="配置Nginx"></a>配置Nginx</h2><h3 id="1-拉取镜像-2"><a href="#1-拉取镜像-2" class="headerlink" title="1. 拉取镜像"></a>1. 拉取镜像</h3><figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">docker pull nginx</div></pre></div></div></figure>
<h3 id="2-运行容器-2"><a href="#2-运行容器-2" class="headerlink" title="2. 运行容器"></a>2. 运行容器</h3><p>我们先运行无挂载的容器，拿到nginx的一些配置文件</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></div><div class="code"><pre><div class="line">docker run \</div><div class="line">-d \</div><div class="line">-p 80:80 \</div><div class="line">--name m_nginx nginx:latest</div></pre></div></div></figure>
<p>成功后，我们进入容器<code>/etc/nginx/</code>文件夹中，我们需要的挂载<code>nginx.conf</code>和<code>conf.d</code>文件夹中的配置文件，因为是我们平时需要频繁更改的配置，所以，我们将他们复制到宿主机上。</p>
<p>退出命令行，不要使用exit，因为exit会让容器停止。这里使用<code>ctrl + p + q</code>来退出容器。</p>
<p>然后使用<code>docker cp</code>操作复制出文件</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></div><div class="code"><pre><div class="line">docker cp m_nginx:/etc/nginx/nginx.conf /data/nginx</div><div class="line">docker cp m_nginx:/etc/nginx/conf.d/default.conf /data/nginx/conf</div></pre></div></div></figure>
<h3 id="3-删除之前运行的Nginx容器"><a href="#3-删除之前运行的Nginx容器" class="headerlink" title="3. 删除之前运行的Nginx容器"></a>3. 删除之前运行的Nginx容器</h3><figure class="highlight zsh"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></div><div class="code"><pre><div class="line">docker stop m_nginx</div><div class="line">docker rm m_nginx</div></pre></div></div></figure>
<h3 id="4-重新运行Nginx容器"><a href="#4-重新运行Nginx容器" class="headerlink" title="4. 重新运行Nginx容器"></a>4. 重新运行Nginx容器</h3><figure class="highlight zsh"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></div><div class="code"><pre><div class="line"><span class="comment"># docker run \</span></div><div class="line">  -d \</div><div class="line">  -p 80:80 \</div><div class="line">  -v /data/wwwroot:/usr/share/nginx/html \</div><div class="line">  -v /data/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \</div><div class="line">  -v /data/nginx/conf:/etc/nginx/conf.d \</div><div class="line">  -v /data/wwwlogs:/var/<span class="built_in">log</span>/nginx \</div><div class="line">  --link m_phpfpm:phpfpm \</div><div class="line">  --name m_nginx nginx:latest</div></pre></div></div></figure>
<blockquote class="question">内容 参数说明：<br> -d 让容器在后台运行<br> -p 添加主机到容器的端口映射<br> -v 添加目录映射,这里最好nginx容器的根目录最好写成和php容器中根目录一样。但是不一点非要一模一样,如果不一样在配置nginx的时候需要注意<br> -–name 容器的名字<br> –-link 与另外一个容器建立起联系</blockquote>

<h3 id="5-编辑配置文件"><a href="#5-编辑配置文件" class="headerlink" title="5. 编辑配置文件"></a>5. 编辑配置文件</h3><p>修改<code>/data/nginx/conf/default.conf</code>，我的配置如下：</p>
<figure class="highlight plain"><div class="figcode"><div class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></div><div class="code"><pre><div class="line">server &#123;</div><div class="line">    listen       80;</div><div class="line">    server_name  _;</div><div class="line"></div><div class="line">    #charset koi8-r;</div><div class="line">    access_log  /var/log/nginx/default_nginx.log  main;</div><div class="line"></div><div class="line">    location / &#123;</div><div class="line">        root   /usr/share/nginx/html/default;</div><div class="line">        index  index.html index.htm;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #error_page  404              /404.html;</div><div class="line"></div><div class="line">    # redirect server error pages to the static page /50x.html</div><div class="line">    #</div><div class="line">    error_page   500 502 503 504  /50x.html;</div><div class="line">    location = /50x.html &#123;</div><div class="line">        root   /usr/share/nginx/html;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    # proxy the PHP scripts to Apache listening on 127.0.0.1:80</div><div class="line">    #</div><div class="line">    #location ~ \.php$ &#123;</div><div class="line">    #    proxy_pass   http://127.0.0.1;</div><div class="line">    #&#125;</div><div class="line"></div><div class="line">    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000</div><div class="line">    #</div><div class="line">    location ~ \.php$ &#123;</div><div class="line">        root           /usr/share/nginx/html/default;</div><div class="line">        fastcgi_pass   phpfpm:9000;</div><div class="line">        fastcgi_index  index.php;</div><div class="line">        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;</div><div class="line">        include        fastcgi_params;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    # deny access to .htaccess files, if Apache&apos;s document root</div><div class="line">    # concurs with nginx&apos;s one</div><div class="line">    #</div><div class="line">    #location ~ /\.ht &#123;</div><div class="line">    #    deny  all;</div><div class="line">    #&#125;</div><div class="line">&#125;</div></pre></div></div></figure>
<p>配置文件中的<code>fastcgi_pass phpfpm:9000;</code>，因为我们在启动容器的时候<code>--link</code>了<code>phpfpm</code>容器，所以这里直接填<code>phpfpm</code>，就能找到<code>phpfpm</code>的IP，当然你也可以不配置<code>--link</code>，那么你可以这样找到容器IP，再将IP填入。</p>
<figure class="highlight bash"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">docker inspect 容器名或ID | grep <span class="string">"IPAddress"</span></div></pre></div></div></figure>
<p>最后，我们来测试一下配置是否成功</p>
<p><img src="http://static.notemi.cn/notemi/2018/04/1903420531.png" alt="q1.png"></p>
<h2 id="安装phpMyAdmin"><a href="#安装phpMyAdmin" class="headerlink" title="安装phpMyAdmin"></a>安装phpMyAdmin</h2><p>安装个phpMyAdmin，顺便测试一下MYSQL</p>
<h3 id="1-下载解压"><a href="#1-下载解压" class="headerlink" title="1. 下载解压"></a>1. 下载解压</h3><p>下载地址：<a href="https://www.phpmyadmin.net/" rel="external nofollow noopener noreferrer" target="_blank">https://www.phpmyadmin.net/</a></p>
<p>解压到<code>/data/wwwroot/default</code>，并将文件夹重命名为<code>phpMyAdmin</code></p>
<h3 id="2-配置phpMyAdmin"><a href="#2-配置phpMyAdmin" class="headerlink" title="2. 配置phpMyAdmin"></a>2. 配置phpMyAdmin</h3><p>打开 libraries 目录下，找到config.sample.inc.php，改名为config.inc.php，用文本编辑器打开文件。</p>
<p>在<code>blowfish_secret</code>中填入值，如：</p>
<figure class="highlight sql"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">$cfg['blowfish_secret'] = 'sadsadsadasffdsadfsa'; <span class="comment">/* YOU MUST FILL IN THIS FOR COOKIE AUTH! */</span></div></pre></div></div></figure>
<p>在<code>host</code>中填入数据库的访问IP，这里我填的Mysql容器的内网IP，你也可以填外网IP试试。</p>
<figure class="highlight sql"><div class="figcode"><div class="gutter"><pre><div class="line">1</div></pre></div><div class="code"><pre><div class="line">$cfg['Servers'][$i]['host'] = '172.17.0.2';</div></pre></div></div></figure>
<p>保存退出</p>
<h3 id="3-访问"><a href="#3-访问" class="headerlink" title="3. 访问"></a>3. 访问</h3><p>访问<code>http://外网IP/phpMyAdmin/index.php</code></p>
<p><img src="http://static.notemi.cn/notemi/2018/04/4034020030.png" alt="q2.png"></p>
<p>用数据库账号密码登录</p>
<p><img src="http://static.notemi.cn/notemi/2018/04/409938554.png" alt="q3.png"></p>
<p>ojbk！ <img src="https://notemi.cn/usr/plugins/Smilies/hangout/icon_lol.png" alt="icon_lol.png"></p>
<hr>
      
    </div>

    
      


    

    
    
    
    
    <div>
        
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
    </div>
    
    <div>
          
            
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/docker-quickly-build-php-nginx-mysql-environment.html">docker快速搭建php nginx mysql环境</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 yszar 的个人博客">yszar</a></p>
  <p><span>发布时间:</span>2018年10月07日 - 15:10</p>
  <p><span>最后更新:</span>2018年11月02日 - 23:11</p>
  <p><span>原始链接:</span><a href="/docker-quickly-build-php-nginx-mysql-environment.html" title="docker快速搭建php nginx mysql环境">https://blog.codenote.pro/docker-quickly-build-php-nginx-mysql-environment.html</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fas fa-copy" data-clipboard-text="https://blog.codenote.pro/docker-quickly-build-php-nginx-mysql-environment.html" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="external nofollow noopener noreferrer" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>


          
    </div>

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="yszar wechat" style="width: 200px; max-width: 100%;">
    <div>欢迎您扫一扫上面的微信公众号，订阅我的博客！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/uploads/wxfk.png" alt="yszar 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/uploads/zfbfk.png" alt="yszar 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"><i class="fa fa-tag"></i> linux</a>
          
            <a href="/tags/docker/" rel="tag"><i class="fa fa-tag"></i> docker</a>
          
            <a href="/tags/php/" rel="tag"><i class="fa fa-tag"></i> php</a>
          
            <a href="/tags/nginx/" rel="tag"><i class="fa fa-tag"></i> nginx</a>
          
            <a href="/tags/mysql/" rel="tag"><i class="fa fa-tag"></i> mysql</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        
          <div class="wp_rating">
          <div style="color: rgba(0, 0, 0, 0.75); font-size:13px; letter-spacing:3px">(&gt;看完记得五星好评哦亲&lt;)</div>
            <div id="wpac-rating"></div>
          </div>
        

        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
            
              
              <a href="/how-to-write-dockercomposeyml.html" rel="prev" title="如何写docker-compose.yml">
                
                <i class="fa fa-chevron-left"></i> 如何写docker-compose.yml
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
            
              
              <a href="/this-blog-hexo-next-githubpages-optimization.html" rel="next" title="本博客Hexo NexT GitHubPages优化">
                
                本博客Hexo NexT GitHubPages优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
       <div id="gitalk-container"></div>
       <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">yszar</p>
              <p class="site-description motion-element" itemprop="description">学无止境！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">21</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yszar" target="_blank" title="GitHub" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yszar@vip.qq.com" target="_blank" title="E-Mail" rel="external nofollow noopener noreferrer"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow noopener noreferrer">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          

          
            
          
          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#目标"><span class="nav-number">1.</span> <span class="nav-text">目标</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装Docker"><span class="nav-number">2.</span> <span class="nav-text">安装Docker</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建资源文件夹"><span class="nav-number">3.</span> <span class="nav-text">创建资源文件夹</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#部署Mysql"><span class="nav-number">4.</span> <span class="nav-text">部署Mysql</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-拉取镜像"><span class="nav-number">4.1.</span> <span class="nav-text">1. 拉取镜像</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-运行容器"><span class="nav-number">4.2.</span> <span class="nav-text">2. 运行容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-进入容器"><span class="nav-number">4.3.</span> <span class="nav-text">3. 进入容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-开启Mysql远程连接"><span class="nav-number">4.4.</span> <span class="nav-text">4. 开启Mysql远程连接</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#部署PHP"><span class="nav-number">5.</span> <span class="nav-text">部署PHP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-拉取镜像-1"><span class="nav-number">5.1.</span> <span class="nav-text">1. 拉取镜像</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-运行容器-1"><span class="nav-number">5.2.</span> <span class="nav-text">2. 运行容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-创建php文件"><span class="nav-number">5.3.</span> <span class="nav-text">3. 创建php文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置Nginx"><span class="nav-number">6.</span> <span class="nav-text">配置Nginx</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-拉取镜像-2"><span class="nav-number">6.1.</span> <span class="nav-text">1. 拉取镜像</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-运行容器-2"><span class="nav-number">6.2.</span> <span class="nav-text">2. 运行容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-删除之前运行的Nginx容器"><span class="nav-number">6.3.</span> <span class="nav-text">3. 删除之前运行的Nginx容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-重新运行Nginx容器"><span class="nav-number">6.4.</span> <span class="nav-text">4. 重新运行Nginx容器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-编辑配置文件"><span class="nav-number">6.5.</span> <span class="nav-text">5. 编辑配置文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装phpMyAdmin"><span class="nav-number">7.</span> <span class="nav-text">安装phpMyAdmin</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-下载解压"><span class="nav-number">7.1.</span> <span class="nav-text">1. 下载解压</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-配置phpMyAdmin"><span class="nav-number">7.2.</span> <span class="nav-text">2. 配置phpMyAdmin</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-访问"><span class="nav-number">7.3.</span> <span class="nav-text">3. 访问</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  
  <span class="with-love" id="heart">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yszar</span>

  

  
</div>


  










<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共38.6k字</span>
</div>
<div class="post-count">
	<a href="http://www.miitbeian.gov.cn/" rel="external nofollow noopener noreferrer" target="_blank">陇ICP备15003024号</a>
</div>


<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，订阅本博客</div>
    </div>
  </div>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










   
     
       <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

      <script src="/js/src/md5.min.js"></script>

       <script type="text/javascript">
         const gitalk = new Gitalk({
           clientID: '54f26977793794b45255',
           clientSecret: '568cccb3bdde42eca6c05ab0680b4617bbb58c4f',
           repo: 'yszar.github.io',
           owner: 'yszar',
           admin: 'yszar'.split(','),
           id: md5(location.pathname),
           pagerDirection: 'first',
           // facebook-like distraction free mode
           distractionFreeMode: false
         })
         gitalk.render('gitalk-container')
       </script>
     
   
 
  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "iUS887d8BnkY3Gqc9FJX70fE-gzGzoHsz",
                'X-LC-Key': "ekF4kKyQDgrDkIBadj3IDrVA",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  <script type="text/javascript">
  wpac_init = window.wpac_init || [];
  wpac_init.push({widget: 'Rating', id: 14244,
    el: 'wpac-rating',
    color: 'fc6423'
  });
  (function() {
    if ('WIDGETPACK_LOADED' in window) return;
    WIDGETPACK_LOADED = true;
    var mc = document.createElement('script');
    mc.type = 'text/javascript';
    mc.async = true;
    mc.src = '//embed.widgetpack.com/widget.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
  })();
  </script>


  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('复制成功')
          else $(this).text('复制失败')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('复制')
        }, 300)
      }).append(e)
    })
  </script>


  
</body>
</html>
